#include "qudpserver.h"
#include "CControlManage.h"

NETWORKSERVICE_BEGIN_NAMESPACE

QUdpServer::QUdpServer(QObject *parent)
    : QObject{parent}
{

}

void QUdpServer::readDataSlots()
{

    while (udpSocket.hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(udpSocket.pendingDatagramSize());
        QHostAddress senderAddress;
        quint16 senderPort;
        udpSocket.readDatagram(datagram.data(), datagram.size(), &senderAddress, &senderPort);

        // 处理接收到的数据
        //qDebug() << "Received datagram:" << datagram;
        emit recvData(senderAddress, senderPort, datagram);

        if(datagram.size() <= 0){
            qDebug("iDataLen <= 0, iDataLen=%d", datagram.size());
            return;
        }

        qDebug("RECV:ip=%s, data=%s", senderAddress.toString().toStdString().c_str(), datagram.data());

        bool isAuthorizationSuccess = false;

        T_CmdBaseData baseData;
        baseData.loadJsonString(datagram.data());

        string signature = controlManage::strMd5(controlManage::strMd5(baseData.sendMsgId + QString::number(baseData.timestamp).toStdString()));
        if(!signature.empty() && signature == baseData.signature){
            isAuthorizationSuccess = true;
        }

        qDebug("signature=%s, data=%s", signature.c_str(), baseData.signature.c_str());

        struct tRoute route;
        route.type = ROUTE_UDP_CLIENT;
        route.udpIp = senderAddress.toString().toStdString();
        route.port = senderPort;
        route.isAuthorizationSuccess = isAuthorizationSuccess;
        string body = string(datagram.data(), datagram.size());
        controlManage::runUdpHandle(&baseData, body, &route);
    }
}

// 启动
bool QUdpServer::start(quint16 port)
{


    if(!udpSocket.bind(QHostAddress::AnyIPv4, port)){
        return false;
    }

    QObject::connect(&udpSocket, &QUdpSocket::readyRead, this, &QUdpServer::readDataSlots);

    return true;
}

bool QUdpServer::sendDataToIp(const string &ip, const string &data)
{

    QHostAddress targetAddress(QString::fromStdString(ip));
    quint16 targetPort = COMM_ENTRANCE_UDP_PORT;
    QString message = QString::fromStdString(data);
    QByteArray datagram = message.toUtf8();
    if(ip.empty()){
        targetAddress = QHostAddress::Broadcast;
    }
    qint64 ret = udpSocket.writeDatagram(datagram, targetAddress, targetPort);
    return ret == datagram.size();
}
NETWORKSERVICE_END_NAMESPACE
